﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ZYStudios.Filter;
using System.Xml.Linq;
using ZYStudios.Common;
using DoubanApi.Models;
using ZYStudios.Models;
using Ext.Net;
using Ext.Net.MVC;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;



namespace ZYStudios.Controllers
{
    public class AdminController : BaseController
    {
        #region Admin Manage
        [AdminFilter(Order = 0)]
        public ActionResult Index()
        {
            ViewData["UserName"] = "管理员";
            if (HttpContext.Application["TodayAccessCount"] == null)
            {
                ViewData["TodayAccessCount"] = 0;
            }
            else
            {
                ViewData["TodayAccessCount"] = HttpContext.Application["TodayAccessCount"];
            }

            ViewData["TotalAccessCount"] = System.IO.File.ReadAllText(HttpContext.Server.MapPath("/TotalAccess.txt"));

            return View();
        }


        public ActionResult Login()
        {
            return this.View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string txtUsername, string txtPassword, string returnUrl)
        {
            if (!(txtUsername == Properties.Settings.Default.AdminName && txtPassword == Properties.Settings.Default.AdminPwd))
            {
                return new AjaxResult { ErrorMessage = "用户名或密码错误！" };
            }

            Session["IsAdminLogin"] = true;

            return this.RedirectToAction("Index", "Admin");
        }


        public ActionResult Logout()
        {
            Session["IsAdminLogin"] = false;
            return RedirectToAction("Login", "Admin");
        }

        [AdminFilter]
        public ActionResult Dashboard()
        {
            return this.View();
        }

        [AdminFilter]
        public AjaxStoreResult GetHomeSchema()
        {
            XElement document = XElement.Load(Server.MapPath("~/Content/Dashboard/HomeSchema.xml"));
            var defaultIcon = document.Attribute("defaultIcon") != null ? document.Attribute("defaultIcon").Value : "";
            var query = from g in document.Elements("group")
                        select new
                        {
                            Title = g.Attribute("title") != null ? g.Attribute("title").Value : "",
                            Items = (from i in g.Elements("item")
                                     select new
                                     {
                                         Title = i.Element("title") != null ? i.Element("title").Value : "",
                                         Icon = i.Element("item-icon") != null ? i.Element("item-icon").Value : defaultIcon,
                                         Accordion = i.Element("accordion-item") != null ? i.Element("accordion-item").Value : "",
                                         MenuItem = i.Element("menu-item") != null ? i.Element("menu-item").Value : ""
                                     }
                                     )
                        };

            return new AjaxStoreResult(query);
        } 
        #endregion

        #region NewMovies
        [AdminFilter]
        public ActionResult NewMovieEdit()
        {
            return View();
        }

        [AdminFilter]
        public AjaxStoreResult GetNewMovies(int limit, int start, string dir, string sort)
        {

            ZYStudios.Models.Data aData = new Models.Data();
            ZYStudios.Models.DataTableAdapters.NewMovieTableAdapter aNewMovieAdapter = new Models.DataTableAdapters.NewMovieTableAdapter();
            aNewMovieAdapter.Fill(aData.NewMovie);
            List<NewMovieEditModel> NewMovieList = new List<NewMovieEditModel>();
            foreach (var row in aData.NewMovie.ToArray())
            {
                NewMovieList.Add(new NewMovieEditModel()
                {
                    ID = row.ID,
                    MovieName = row.MovieName,
                });
            }

            var query = (from c in NewMovieList
                         select c);

            int total = query.ToList().Count;

            query = query.Skip(start).Take(limit);
            return new AjaxStoreResult(query, total);
        }


        [AdminFilter]
        public AjaxStoreResult SaveNewMovies()
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);

            try
            {
                ZYStudios.Models.Data aData = new Models.Data();
                ZYStudios.Models.DataTableAdapters.NewMovieTableAdapter aNewMovieAdapter = new Models.DataTableAdapters.NewMovieTableAdapter();
                aNewMovieAdapter.Fill(aData.NewMovie);

                var aCacheMovieProvide = CreateFileCache();

                StoreDataHandler dataHandler = new StoreDataHandler(HttpContext.Request["data"]);
                ChangeRecords<NewMovieEditModel> data = dataHandler.ObjectData<NewMovieEditModel>();

                foreach (NewMovieEditModel item in data.Deleted)
                {
                    var aModel = aData.NewMovie.FirstOrDefault(p => p.ID == item.ID);
                    if (aModel != null)
                    {
                        aCacheMovieProvide.Remove(aModel.MovieName.GetHashCode().ToString());
                        aCacheMovieProvide.Remove(aModel.MovieID.ToString());
                        aModel.Delete();
                    }
                }

                foreach (NewMovieEditModel item in data.Updated)
                {
                    if (string.IsNullOrWhiteSpace(item.MovieName.Trim()))
                    {
                        continue;
                    }

                    var aMovieItem = aCacheMovieProvide.Get(item.MovieName.GetHashCode().ToString()) as MovieModel;
                    if (aMovieItem == null)
                    {

                        var aModel = aData.NewMovie.FirstOrDefault(p => p.ID == item.ID);
                        if (aModel != null)
                        {
                            aCacheMovieProvide.Remove(aModel.MovieName.GetHashCode().ToString());
                            aCacheMovieProvide.Remove(aModel.MovieID.ToString());
                        }

                        aMovieItem = CreateDoubanApi().SearchMovie(item.MovieName);
                        if (aMovieItem == null)
                        {
                            throw new Exception("未找到影片" + item.MovieName);
                        }
                        if (aMovieItem.Title != item.MovieName)
                        {
                            aMovieItem.Title = item.MovieName;
                            CreateDoubanApi().FindMoviePreviewYouKu(aMovieItem);
                        }
                        else
                        {
                            aMovieItem.Title = item.MovieName;
                        }
                        aCacheMovieProvide.Add(item.MovieName.GetHashCode().ToString(), aMovieItem, DateTime.Now.AddDays(2));
                        aCacheMovieProvide.Add(aMovieItem.Id.ToString(), aMovieItem, DateTime.Now.AddDays(2));
                    }
                    else
                    {
                        aCacheMovieProvide.Remove(item.MovieName.GetHashCode().ToString());
                        aCacheMovieProvide.Remove(item.ID.ToString());
                        if (aMovieItem.Title != item.MovieName)
                        {
                            aMovieItem.Title = item.MovieName;
                            CreateDoubanApi().FindMoviePreviewYouKu(aMovieItem);
                        }
                        else
                        {
                            aMovieItem.Title = item.MovieName;
                        }
                        aCacheMovieProvide.Add(item.MovieName.GetHashCode().ToString(), aMovieItem, DateTime.Now.AddDays(2));
                        aCacheMovieProvide.Add(aMovieItem.Id.ToString(), aMovieItem, DateTime.Now.AddDays(2));
                    }
                    var aNewMovie = aData.NewMovie.SingleOrDefault(p => p.ID == item.ID);
                    aNewMovie.MovieID = aMovieItem.Id.ToString();
                    aNewMovie.MovieName = item.MovieName;


                }

                foreach (NewMovieEditModel item in data.Created)
                {
                    if (string.IsNullOrWhiteSpace(item.MovieName.Trim()))
                    {
                        continue;
                    }

                    var aMovieItem = aCacheMovieProvide.Get(item.MovieName.GetHashCode().ToString()) as MovieModel;
                    if (aMovieItem == null)
                    {
                        aMovieItem = CreateDoubanApi().SearchMovie(item.MovieName);
                        if (aMovieItem == null)
                        {
                            throw new Exception("未找到影片" + item.MovieName);
                        }
                        if (aMovieItem.Title != item.MovieName)
                        {
                            aMovieItem.Title = item.MovieName;
                            CreateDoubanApi().FindMoviePreviewYouKu(aMovieItem);
                        }
                        else
                        {
                            aMovieItem.Title = item.MovieName;
                        }
                        aMovieItem.Title = item.MovieName;
                        aCacheMovieProvide.Add(item.MovieName.GetHashCode().ToString(), aMovieItem, DateTime.Now.AddDays(2));
                        aCacheMovieProvide.Add(aMovieItem.Id.ToString(), aMovieItem, DateTime.Now.AddDays(2));
                    }

                    if (aMovieItem.Title != item.MovieName)
                    {
                        aMovieItem.Title = item.MovieName;
                        CreateDoubanApi().FindMoviePreviewYouKu(aMovieItem);
                    }
                    else
                    {
                        aMovieItem.Title = item.MovieName;
                    }
                    var aNewRow = aData.NewMovie.NewNewMovieRow();
                    aNewRow.MovieID = aMovieItem.Id.ToString();
                    aNewRow.MovieName = item.MovieName;
                    aData.NewMovie.AddNewMovieRow(aNewRow);

                }
                aNewMovieAdapter.Update(aData.NewMovie);
                RemoveMovieIndexCache();
            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success = false;
                ajaxStoreResult.SaveResponse.Message = e.Message;
            }

            return ajaxStoreResult;
        }

       

        [AdminFilter]
        [AcceptVerbs(HttpVerbs.Post)]
        public AjaxFormResult NewMovieImportFromPlaytime()
        {
            AjaxFormResult response = new AjaxFormResult();
            ZYStudios.Models.Data aData = new Models.Data();
            ZYStudios.Models.DataTableAdapters.NewMovieTableAdapter aNewMovieAdapter = new Models.DataTableAdapters.NewMovieTableAdapter();
            aNewMovieAdapter.Fill(aData.NewMovie);

            aData.NewMovie.ToList().ForEach(p => p.Delete());
            aNewMovieAdapter.Update(aData.NewMovie);

            var aPlaytime = PlaytimeHelper.ReadPlayTimeData();
            Dictionary<string, int> aMovieList = new Dictionary<string, int>();
            if (aPlaytime != null)
            {
                foreach (var item in aPlaytime)
                {
                    item.Movies.ForEach(p =>
                    {
                        if (!aMovieList.ContainsKey(p.Movie.Title))
                        {
                            aMovieList.Add(p.Movie.Title, p.Movie.Id);
                        }
                    });
                }
            }

            foreach (string key in aMovieList.Keys)
            {
                aData.NewMovie.AddNewMovieRow(key, aMovieList[key].ToString());
            }
            aNewMovieAdapter.Update(aData.NewMovie);

            RemoveMovieIndexCache();

            return response;
        }
        #endregion

        #region Playtime

        [AdminFilter]
        public ActionResult PlaytimeEdit()
        {
            return View();
        }

        [AdminFilter]
        [AcceptVerbs(HttpVerbs.Post)]
        public AjaxFormResult UploadPlaytime(FormCollection collection)
        {
            AjaxFormResult response = new AjaxFormResult();
            response.IsUpload = true;
            if (Request.Files.Count == 0)
            {
                response.IsUpload = false;
                response.Success = false;
                return response;
            }
            var c = Request.Files[0];
            try
            {
                if (c != null && c.ContentLength > 0)
                {
                    List<PlaytimeModel> aPlayTimeData = PlaytimeHelper.GeneratePlayTime(c.InputStream);
                    PlaytimeHelper.SavePlayTimeData(aPlayTimeData);
                    RemovePlaytimeCache();
                }
                else
                {
                    response.IsUpload = false;
                    response.Success = false;
                    return response;
                }
            }
            catch (Exception ex)
            {
                response.IsUpload = false;
                response.Success = false;
                return response;
            }
            return response;
        }
     
        [AdminFilter]
        public ActionResult PlaytimeEditPanel()
        {
            ViewData["PlayTimeData"] = PlaytimeHelper.ReadPlayTimeData();
            return View();
        }

        [AdminFilter]
        [AcceptVerbs(HttpVerbs.Post)]
        public void PlaytimeEditPanelSubmit(PlaytimeItemModel[] aPlaytimeItemList)
        {
            List<PlaytimeModel> aPlayTimeData = PlaytimeHelper.ReadPlayTimeData();

            if (aPlayTimeData != null)
            {
                var aCacheMovieProvide = CreateFileCache();

                foreach (var PlayTimeDataItem in aPlayTimeData)
                {
                    var aTempPlaytimeItemList = aPlaytimeItemList.Where(p => p.ParentId == PlayTimeDataItem.Id);
                    foreach (var aTempItem in aTempPlaytimeItemList)
                    {
                        var aItem = PlayTimeDataItem.Movies.SingleOrDefault(p => p.Id == aTempItem.Id);
                        if (aItem != null)
                        {

                            aItem.PlayTime = aTempItem.PlayTime;
                            aItem.MovieDuration = aTempItem.MovieDuration;

                            if (aItem.MovieName != aTempItem.MovieName)
                            {
                                var aMovieItem = aCacheMovieProvide.Get(aItem.MovieName.GetHashCode().ToString()) as MovieModel;
                                if (aMovieItem != null)
                                {
                                    aCacheMovieProvide.Remove(aItem.MovieName.GetHashCode().ToString());
                                    aCacheMovieProvide.Remove(aItem.Movie.Id.ToString());

                                    aItem.MovieName = aTempItem.MovieName;
                                    aMovieItem.Title = aTempItem.MovieName;

                                    aCacheMovieProvide.Add(aItem.MovieName.GetHashCode().ToString(), aMovieItem, DateTime.Now.AddDays(2));
                                    aCacheMovieProvide.Add(aMovieItem.Id.ToString(), aMovieItem, DateTime.Now.AddDays(2));
                                }
                            }
                        }
                    }
                }

                PlaytimeHelper.SavePlayTimeData(aPlayTimeData);
            }

            RemovePlaytimeCache();
        }

        #endregion

        #region IndexImages
        [AdminFilter]
        public ActionResult IndexImageEdit()
        {
            return View();
        }

        [AdminFilter]
        public AjaxStoreResult GetIndexImages(int limit, int start, string dir, string sort)
        {
            ZYStudios.Models.Data aData = new Models.Data();
            ZYStudios.Models.DataTableAdapters.IndexImageTableAdapter aIndexImageAdapter = new Models.DataTableAdapters.IndexImageTableAdapter();
            aIndexImageAdapter.Fill(aData.IndexImage);
            List<IndexImageEditModel> IndexImageList = new List<IndexImageEditModel>();
            foreach (var row in aData.IndexImage.ToArray())
            {
                IndexImageList.Add(new IndexImageEditModel()
                {
                    ID = row.ID,
                    ImageUrl = row.ImageUrl,
                    ImageLink = row.ImageLink
                });
            }

            var query = (from c in IndexImageList
                         select c);

            int total = query.ToList().Count;

            query = query.Skip(start).Take(limit);
            return new AjaxStoreResult(query, total);
        }

        [AdminFilter]
        public AjaxStoreResult SaveIndexImages()
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);

            try
            {
                ZYStudios.Models.Data aData = new Models.Data();
                ZYStudios.Models.DataTableAdapters.IndexImageTableAdapter aIndexImageAdapter = new Models.DataTableAdapters.IndexImageTableAdapter();
                aIndexImageAdapter.Fill(aData.IndexImage);

                var aCacheMovieProvide = CreateFileCache();

                StoreDataHandler dataHandler = new StoreDataHandler(HttpContext.Request["data"]);
                ChangeRecords<IndexImageEditModel> data = dataHandler.ObjectData<IndexImageEditModel>();

                foreach (IndexImageEditModel item in data.Updated)
                {
                    var aModel = aData.IndexImage.SingleOrDefault(p => p.ID == item.ID);
                    aModel.ImageLink = item.ImageLink;
                    aIndexImageAdapter.Update(aData.IndexImage);
                }

                foreach (IndexImageEditModel item in data.Deleted)
                {
                    aData.IndexImage.SingleOrDefault(p => p.ID == item.ID).Delete();
                    aIndexImageAdapter.Update(aData.IndexImage);
                    System.IO.File.Delete(Server.MapPath(item.ImageUrl));
                }

                RemoveIndexImageCache();
            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success = false;
                ajaxStoreResult.SaveResponse.Message = e.Message;
            }

            return ajaxStoreResult;
        }

 

        [AdminFilter]
        [AcceptVerbs(HttpVerbs.Post)]
        public AjaxFormResult UploadIndexImage(FormCollection collection)
        {

            AjaxFormResult response = new AjaxFormResult();
            response.IsUpload = true;
            if (Request.Files.Count == 0)
            {
                response.IsUpload = false;
                response.Success = false;
                return response;
            }
            var c = Request.Files[0];
            try
            {
                if (c != null && c.ContentLength > 0)
                {
                    string aFileName = Guid.NewGuid().ToString();
                    string aFilePath = HttpContext.Server.MapPath("/Content/Images/slide/" + aFileName + ".jpg");
                    c.SaveAs(aFilePath);

                    ZYStudios.Models.Data aData = new Models.Data();
                    ZYStudios.Models.DataTableAdapters.IndexImageTableAdapter aIndexImageAdapter = new Models.DataTableAdapters.IndexImageTableAdapter();
                    aIndexImageAdapter.Fill(aData.IndexImage);
                    aData.IndexImage.AddIndexImageRow("/Content/Images/slide/" + aFileName + ".jpg", "");
                    aIndexImageAdapter.Update(aData.IndexImage);

                    Thumbnail.GetThumbnail(aFilePath, aFilePath, 261, 660);

                    RemoveIndexImageCache();
                }
                else
                {
                    response.IsUpload = false;
                    response.Success = false;
                    return response;
                }
                c.InputStream.Close();
            }
            catch (Exception ex)
            {
                c.InputStream.Close();
                response.IsUpload = false;
                response.Success = false;
                return response;
            }


            return response;
        }


        [AdminFilter]
        //[AcceptVerbs(HttpVerbs.Post)]
        public ContentResult UploadImage(FormCollection collection)
        {
            ContentResult response = new ContentResult();
            string aUrl = "";

            if (Request.Files.Count == 0)
            {
                response.Content = "{success:true,\"state\":\"error\",\"msg\":\"" + "没有文件" + "\"}";
                return response;
            }
            var c = Request.Files[0];
            try
            {
                if (c != null && c.ContentLength > 0)
                {
                    string aFileName = Guid.NewGuid().ToString();
                    string aUrlPath = "/Content/Images/User/" + aFileName + c.FileName.Substring(c.FileName.LastIndexOf('.'));
                    string aFilePath = HttpContext.Server.MapPath(aUrlPath);
                    c.SaveAs(aFilePath);
                    aUrl = aUrlPath;
                }
                else
                {
                    response.Content = "{success:true,\"state\":\"error\",\"msg\":\"" + "未知错误" + "\"}";
                    return response;
                }
                c.InputStream.Close();
            }
            catch (Exception ex)
            {
                c.InputStream.Close();

                response.Content = "{success:true,\"state\":\"error\",\"msg\":\"" + ex.Message + "\"}";
                return response;
            }

            response.Content = "{success:true,\"state\":\"ok\",\"aUrl\":\"" + aUrl + "\"}";
            return response;
        }
        #endregion

        #region Link
        [AdminFilter]
        public ActionResult LinksEdit()
        {
            return View();
        }

        [AdminFilter]
        public AjaxStoreResult GetLinks(int limit, int start, string dir, string sort)
        {
            ZYStudios.Models.Data aData = new Models.Data();
            ZYStudios.Models.DataTableAdapters.LinksTableAdapter aLinksAdapter = new Models.DataTableAdapters.LinksTableAdapter();
            aLinksAdapter.Fill(aData.Links);
            List<LinkEditModel> LinksList = new List<LinkEditModel>();
            foreach (var row in aData.Links.ToArray())
            {
                LinksList.Add(new LinkEditModel()
                {
                    ID = row.ID,
                    Link = row.Link,
                    LinkImage = row.LinkImage,
                    LinkName = row.LinkName
                });
            }

            var query = (from c in LinksList
                         select c);

            int total = query.ToList().Count;

            query = query.Skip(start).Take(limit);
            return new AjaxStoreResult(query, total);
        }

        [AdminFilter]
        public AjaxStoreResult SaveLinks()
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);

            try
            {
                ZYStudios.Models.Data aData = new Models.Data();
                ZYStudios.Models.DataTableAdapters.LinksTableAdapter aLinksAdapter = new Models.DataTableAdapters.LinksTableAdapter();
                aLinksAdapter.Fill(aData.Links);

                var aCacheMovieProvide = CreateFileCache();

                StoreDataHandler dataHandler = new StoreDataHandler(HttpContext.Request["data"]);
                ChangeRecords<LinkEditModel> data = dataHandler.ObjectData<LinkEditModel>();

                foreach (LinkEditModel item in data.Deleted)
                {
                    aData.Links.SingleOrDefault(p => p.ID == item.ID).Delete();
                }
                foreach (LinkEditModel item in data.Updated)
                {
                    var aLink = aData.Links.SingleOrDefault(p => p.ID == item.ID);
                    aLink.LinkName = item.LinkName;
                    aLink.Link = item.Link;
                    aLink.LinkImage = item.LinkImage;
                }

                foreach (LinkEditModel item in data.Created)
                {
                    aData.Links.AddLinksRow(item.LinkName, item.Link, item.LinkImage);
                }
                aLinksAdapter.Update(aData.Links);
                string aPath = Server.MapPath("/Cache/");
                foreach (string aFileName in System.IO.Directory.EnumerateFiles(aPath))
                {
                    System.IO.File.Delete(aFileName);
                }

            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success = false;
                ajaxStoreResult.SaveResponse.Message = e.Message;
            }

            return ajaxStoreResult;
        }
        #endregion

        #region Activity
        [AdminFilter]
        public ActionResult ActivitysEdit()
        {
            return View();
        }

        [AdminFilter]
        public AjaxStoreResult GetActivitys(int limit, int start, string dir, string sort)
        {
            ZYStudios.Models.Data aData = new Models.Data();
            ZYStudios.Models.DataTableAdapters.ActivityTableAdapter aActivitysAdapter = new Models.DataTableAdapters.ActivityTableAdapter();
            aActivitysAdapter.Fill(aData.Activity);
            List<ActivityEditModel> ActivitysList = new List<ActivityEditModel>();
            foreach (var row in aData.Activity.ToArray())
            {
                ActivitysList.Add(new ActivityEditModel()
                {
                    ID = row.ID,
                    ActivityContent = row.ActivityContent,
                    ActivityName = row.ActivityName
                });
            }

            var query = (from c in ActivitysList
                         select c);

            int total = query.ToList().Count;

            query = query.Skip(start).Take(limit);
            return new AjaxStoreResult(query, total);
        }

        [AdminFilter]
        [ValidateInput(false)]
        public AjaxStoreResult SaveActivitys()
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);

            try
            {
                ZYStudios.Models.Data aData = new Models.Data();
                ZYStudios.Models.DataTableAdapters.ActivityTableAdapter aActivitysAdapter = new Models.DataTableAdapters.ActivityTableAdapter();
                aActivitysAdapter.Fill(aData.Activity);

                StoreDataHandler dataHandler = new StoreDataHandler(HttpContext.Request["data"]);
                ChangeRecords<ActivityEditModel> data = dataHandler.ObjectData<ActivityEditModel>();

                foreach (ActivityEditModel item in data.Deleted)
                {
                    aData.Activity.SingleOrDefault(p => p.ID == item.ID).Delete();
                }
                foreach (ActivityEditModel item in data.Updated)
                {
                    var aActivity = aData.Activity.SingleOrDefault(p => p.ID == item.ID);
                    aActivity.ActivityContent = item.ActivityContent;
                    aActivity.ActivityName = item.ActivityName;
                }

                foreach (ActivityEditModel item in data.Created)
                {
                    aData.Activity.AddActivityRow(item.ActivityName, item.ActivityContent);
                }
                aActivitysAdapter.Update(aData.Activity);


                RemoveActivityCache();


            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success = false;
                ajaxStoreResult.SaveResponse.Message = e.Message;
            }

            return ajaxStoreResult;
        }

   
        #endregion

        #region Message
        [AdminFilter]
        public ActionResult MessagesEdit()
        {
            return View();
        }

        [AdminFilter]
        public AjaxStoreResult GetMessages(int limit, int start, string dir, string sort)
        {
            ZYStudios.Models.Data aData = new Models.Data();
            ZYStudios.Models.DataTableAdapters.MessageTableAdapter aMessagesAdapter = new Models.DataTableAdapters.MessageTableAdapter();
            aMessagesAdapter.Fill(aData.Message);
            List<UserMessageEditModel> MessagesList = new List<UserMessageEditModel>();
            foreach (var row in aData.Message.ToArray())
            {
                
                MessagesList.Add(new UserMessageEditModel()
                {
                    ID = row.ID,
                    Content = row.Content.Replace("<","").Replace(">",""),
                    MessageDate = row.MessageDate,
                    UserName = row.UserName.Replace("<", "").Replace(">", ""),
                    UserPhone = row.UserPhone.Replace("<", "").Replace(">", ""),
                    UserQQ = row.UserQQ.Replace("<", "").Replace(">", ""),
                    UserEmail = row.UserEmail.Replace("<", "").Replace(">", ""),
                    Reply = row.Reply
                });
            }

            var query = (from c in MessagesList
                         select c);

            int total = query.ToList().Count;

            query = query.OrderByDescending(p => p.MessageDate).Skip(start).Take(limit);
            return new AjaxStoreResult(query, total);
        }

        [AdminFilter]
        [ValidateInput(false)]
        public AjaxStoreResult SaveMessages()
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);

            try
            {
                ZYStudios.Models.Data aData = new Models.Data();
                ZYStudios.Models.DataTableAdapters.MessageTableAdapter aMessagesAdapter = new Models.DataTableAdapters.MessageTableAdapter();
                aMessagesAdapter.Fill(aData.Message);

                StoreDataHandler dataHandler = new StoreDataHandler(HttpContext.Request["data"]);
                ChangeRecords<UserMessageEditModel> data = dataHandler.ObjectData<UserMessageEditModel>();

                foreach (UserMessageEditModel item in data.Deleted)
                {
                    aData.Message.SingleOrDefault(p => p.ID == item.ID).Delete();
                }

                foreach (UserMessageEditModel item in data.Updated)
                {
                    var row = aData.Message.FirstOrDefault(p => p.ID == item.ID);
                    row.Reply = item.Reply;
                }


                aMessagesAdapter.Update(aData.Message);

                Response.RemoveOutputCacheItem("/GuestBook/Index.html");
            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success = false;
                ajaxStoreResult.SaveResponse.Message = e.Message;
            }

            return ajaxStoreResult;
        }
        #endregion

        #region RemoveCache

        private void RemovePlaytimeCache()
        {
            Response.RemoveOutputCacheItem("/Movie/Playtime");
            Response.RemoveOutputCacheItem("/Movie/Playtime.html");
            Response.RemoveOutputCacheItem("/");
            Response.RemoveOutputCacheItem("/Default/Index.html");
        }

        private void RemoveMovieIndexCache()
        {
            Response.RemoveOutputCacheItem("/Movie/Index.html");
            Response.RemoveOutputCacheItem("/Movie/Movie.html");
        }


        private void RemoveIndexImageCache()
        {
            Response.RemoveOutputCacheItem("/");
            Response.RemoveOutputCacheItem("/Default/Index.html");
        }

        private void RemoveActivityCache()
        {
            Response.RemoveOutputCacheItem("/");
            Response.RemoveOutputCacheItem("/Default/Index.html");
            Response.RemoveOutputCacheItem("/Activity/Index.html");
        } 
        #endregion
    }
}